package com.lzjn.code.common.base;

import java.sql.*;
import java.util.ResourceBundle;

public class BaseDao {

	private static ResourceBundle resourceBundle;

	static {
		
		resourceBundle = ResourceBundle.getBundle("dbconfig");
	}
	
	public static Connection getConnection() {
		
		Connection connection = null;

		try {
			
			Class.forName(resourceBundle.getString("jdbc.driver"));
			connection = DriverManager.getConnection(resourceBundle.getString("jdbc.url"),
													 resourceBundle.getString("jdbc.username"), 
													 resourceBundle.getString("jdbc.password"));
		}
		catch (ClassNotFoundException cnfe) {

			cnfe.printStackTrace();
		}
		catch (SQLException sqle) {
	
			sqle.printStackTrace();
		}

		return connection;
	}
	
	public static Connection getConnection(String module) {
		
		Connection connection = null;

		try {
			
			Class.forName(resourceBundle.getString(module + ".driver"));
			connection = DriverManager.getConnection(resourceBundle.getString(module + ".url"),
													 resourceBundle.getString(module + ".username"), 
													 resourceBundle.getString(module + ".password"));
		}
		catch (ClassNotFoundException cnfe) {

			cnfe.printStackTrace();
		}
		catch (SQLException sqle) {
	
			sqle.printStackTrace();
		}

		return connection;
	}
	
	public String getLimitSql(String sql, int offset, int limit) {
		
		String driver = resourceBundle.getString("jdbc.driver");
		
		StringBuilder sb = new StringBuilder(sql);
		
		if(driver.contains("mysql")) {
			
			sb.append(" limit ");
			if(offset > 0) {
				sb.append(offset).append(",").append(limit);
			} else {
				sb.append(limit);
			}
		}
		
		return sb.toString();
	}
	
	
	public void CloseConnection(PreparedStatement ps, Connection conn) {
		
		try {
			if(ps != null) {
				ps.close();
			}
			if(conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void CloseConnection(ResultSet rs, PreparedStatement ps, Connection conn) {
		
		try {
			
			if(rs != null) {
				rs.close();
			}
			if(ps != null) {
				ps.close();
			}
			if(conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}
